import { joinObject } from "."
import Auth from "./auth"
import { ServiceStatusCode } from "./const-value"
import { merge, get, set, isObject } from "lodash"
import { t } from "@/locale"

const { VITE_TOKEN_TYPE, VITE_REQUEST_BASE_URL, VITE_REQUEST_URL } = import.meta.env
export function request<
  T = boolean | null,
  E = ResponseData<T>,
>(
  options: RequestOptions<T, E>,
  reqTask = (_task: UniApp.RequestTask) => { }
) {
  return new Promise<OriginalResponseData<T, E>>((resolve, reject) => {
    let reqFun: (...args: any[]) => any
    const dc = <RequiredDeep<typeof options>>{
      header: {
        "Cache-Control": 'no-cache',
        validate: {
          key: 'code',
          val: ServiceStatusCode.SuccessCode,
        },
        requestBaseUrl: VITE_REQUEST_BASE_URL,
        requestUrl: VITE_REQUEST_URL
      },
      timeout: 10 * 3000,
      success: result => {
        if (dc.header.responseIsJsonString) {
          try {
            result.data = JSON.parse(result.data as unknown as string)
          } catch (error) {
            reject(error)
          }
        }
        if(dc.header.validate.valIsEmpty)
          dc.header.validate.val = options.header?.validate?.val
        if (get(result.data, dc.header.validate.key) 
          === dc.header.validate.val) return resolve(result)
        if (result.statusCode === ServiceStatusCode.LoginExpired) {

        }
        if (result.statusCode === ServiceStatusCode.ServiceErr) {

        }
        set(result, 'data', isObject(result.data) ? result.data : {})
        // Object(result).data.msg = t(`error.${Object(result).data.code}`)
        reject(result)
      },
      fail: result => {
        console.log(result)
        reject(t('other.netWorkError'))
      }
    }

    if (Auth.get()) dc.header.Authorization = VITE_TOKEN_TYPE + Auth.get()
    if (options?.filePath) {
      reqFun = uni.downloadFile
      dc.header.responseIsJsonString = true
    } else {
      reqFun = uni.request
      dc.header["Content-Type"] = 'application/json'
    }
    merge(dc, options)

    if (dc.state) dc.url = dc.url.split('?').reduce((p, c, i) => p + c + (dc.state[i] ?? ''), '')
    if (dc.query) dc.url += joinObject(dc.query)

    dc.url = dc.header.requestBaseUrl + dc.url
    // #ifndef H5
    dc.url = dc.header.requestUrl + dc.url
    // #endif

    reqTask(reqFun(dc))
  })
}